// pages/home/index.js
const util = require('../../utils/util.js')
const config = require('../../utils/config.js')
const App = getApp()
const TYPE = {
  HOT: 'ishot',
  NEW: 'isnew',
  DISCOUNT: 'isdiscount',
  RECOMMAND: 'isrecommand'
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navStyle: [],
    apiUrl: util.apiUrl,
    topNavImage: util.Background_base64('static/image/home/banner.jpg'),
    isLogin: false,
    searchValue: '', //搜索框的值
    searchTop: 0,
    searchWidth: null,
    //搜索框固定
    isSticky: false,
    opacity: 0,
    topDisplay: 'none',
    containerScrollTop: null,
    scrollTop: 0,
    //定位地址
    position: null,
    pageSize: 10,
    currentPage: 1,
    //默认商品列表
    goodsTabType: 'RECOMMAND',
    loadmore: 'end',
    loading: true,
    recommend: config.recommend,
    cateList: [] /* 商品分类列表 */,
    goodList: [],
    discountList: []
    // popVisible: true
  },

  // 获取商品分类
  getCate() {
    try {
      util.request('/api/goods/cate', {}, 'GET').then((response) => {
        if (response.data.code == 0) {
          const data = response.data.data
          const chunkSize = 10
          const newCateList = []

          if (data.length <= 0) return

          for (let i = 0; i < data.length; i += chunkSize) {
            newCateList.push(data.slice(i, i + chunkSize))
          }

          this.setData({
            cateList: newCateList
          })
        }
      })
    } catch (error) {
      console.log(error)
    }
  },

  //获取商品数据
  getData(type, isSwitch = false) {
    if (isSwitch) {
      this.data.currentPage = 1
      this.setData({ loading: true })
    }
    const params = {
      lat: this.data.position ? this.data.position.lat : 0,
      lng: this.data.position ? this.data.position.lng : 0,
      page: this.data.currentPage,
      limit: this.data.pageSize
    }
    params[TYPE[type]] = 1

    try {
      util.request('/api/goods/index', params, 'GET').then((res) => {
        this.setData({
          loading: false
        })
        const result = res.data
        if (result.code !== 0) return

        var datas = result.data
        if (datas.length > 0) {
          if (isSwitch) {
            this.setData({
              goodList: datas /* 商品列表 */
            })
          } else {
            this.setData({
              goodList: this.data.goodList.concat(datas)
            })
          }

          wx.lin.renderWaterFlow(datas, isSwitch, () => {
            this.setData({
              loadmore: 'end'
            })
          })
        } else {
          this.setData({
            loadmore: 'end'
          })
        }
      })
    } catch (err) {
      wx.showToast({
        title: err
      })
    }
  },
  //获取折扣商品数据
  getDiscountData(type) {
    const params = {
      lat: this.data.position ? this.data.position.lat : 0,
      lng: this.data.position ? this.data.position.lng : 0,
      page: 1,
      limit: 9
    }
    params[TYPE[type]] = 1

    try {
      util.request('/api/goods/index', params, 'GET').then((res) => {
        const result = res.data
        if (result.code !== 0) return

        var datas = result.data
        if (datas.length > 0) {
          const chunkSize = 3
          const newGoodsList = []

          for (let i = 0; i < datas.length; i += chunkSize) {
            newGoodsList.push(datas.slice(i, i + 3))
          }
          this.setData({
            discountList: newGoodsList /* 折扣商品列表 */
          })
        }
      })
    } catch (err) {
      wx.showToast({
        title: err
      })
    }
  },
  //跳转折扣页
  gotoDiscount() {
    wx.navigateTo({
      url: '/modules/goodsModule/pages/goodsdiscount/goodsdiscount?type=DISCOUNT'
    })
  },

  // 首页搜索事件
  SearchHome() {
    if (!!this.data.searchValue) {
      wx.navigateTo({
        url: '/modules/goodsModule/pages/goodslist/goodslist?kw=' + this.data.searchValue
      })
    } else {
      wx.showToast({
        title: '请输入关键字！',
        icon: 'none'
      })
    }
  },

  //广告位
  // handleTap(e){
  //   wx.switchTab({
  //     url: '/pages/shoplist/shoplist',
  //   });
  // },

  /**
   * 跳转商品详情页
   */
  goodsInfo(e) {
    let id = null
    if (e.detail.item) {
      id = e.detail.item.id
    } else {
      id = e.currentTarget.dataset.item.id
    }

    wx.navigateTo({
      url: '/modules/goodsModule/pages/goodsinfo/goodsinfo?id=' + id
    })
  },
  gtShopList(e) {
    App.globalData.cateid = e.currentTarget.dataset.cateid
    wx.switchTab({
      url: '/pages/shoplist/shoplist',
      success: function (e) {
        const page = getCurrentPages().pop()
        if (page == undefined || page == null) return
        page.onLoad()
        page.onReady()
      }
    })
  },
  bindgetuserinfo() {
    wx.navigateTo({
      url: '/pages/gologin/gologin'
    })
  },

  getAddressList() {
    try {
      util.request('/api/address/index', {}, 'GET', null, false, true).then((res) => {
        let datas = res.data
        if (datas.code !== 0) return

        let position = datas.data.find((item) => item.is_default === 1)
        if (!position) position = datas.data[0]

        wx.setStorageSync('position', position)
        App.globalData.position = position
        this.setData({ position })

        console.log('position设置成功', position)
      })
    } catch (err) {
      console.log(err)
    }
  },

  /**
   * 调取微信接口调起地图选择地址
   */
  async chooseLocation() {
    let pos = null
    if (this.data.position) {
      pos = {
        latitude: this.data.position.lat,
        longitude: this.data.position.lng
      }
    }

    try {
      const res = await wx.chooseLocation(pos)
      const addressInfo = util.parseAddress(res.address)
      const { province, city, area, detail } = addressInfo
      const { name, latitude, longitude } = res

      const position = {
        province,
        city,
        area,
        street: detail + name,
        lat: latitude,
        lng: longitude
      }
      if (!!detail) {
        wx.setStorageSync('position', position)
        this.setData({ position })
      } else {
        console.error('选择位置失败', err)
      }
    } catch (error) {
      console.log('选择位置失败', error)
    }
  },

  /**
   * 获取购物车商品数量
   */
  getProductConut() {
    util.request('/api/cart/index', {}, 'GET', null, false, true).then((response) => {
      let res = response.data
      if (res.code === 0 && res.data.cart_list.length !== 0) {
        const newList = res.data.cart_list
        //设置购物车缓存
        wx.setStorageSync('cart', newList)
        //计算购物车数量
        util.setCartCount(newList)
      }
    })
  },

  /**
   * tab页切换
   */
  changeTabs(e) {
    const { activeKey } = e.detail
    if (activeKey === this.data.goodsTabType) return

    this.data.goodsTabType = activeKey
    this.getData(this.data.goodsTabType, true)
  },

  /**
   *
   * 优惠活动弹窗
   */
  // handlePopup() {
  //   this.setData({ popVisible: true })
  // },
  // onVisibleChange(e) {
  //   console.log(e)
  //   this.setData({
  //     popVisible: e.detail.visible
  //   })
  // },
  // onClose() {
  //   this.setData({
  //     popVisible: false
  //   })
  // },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let position = wx.getStorageSync('position')
    const token = wx.getStorageSync('token')
    if (!position) {
      this.getAddressList()
    } else {
      App.globalData.position = position
      this.setData({ position })
    }

    if (token) {
      const isLogin = true
      if (this.data.isLogin !== isLogin) {
        this.setData({ isLogin })
      }
    }

    //获取折扣商品
    this.getDiscountData('DISCOUNT')
    //获取推荐商品
    this.getData(this.data.goodsTabType)
    // 获取商品分类
    this.getCate()
    //设置购物车数量
    this.getProductConut()
    // 动态设置 tabBar 的整体样式
    this.setData({
      navStyle: App.globalData,
      searchWidth: App.globalData.windowWidth - 20,
      searchTop: App.globalData.navHeight
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let query = wx.createSelectorQuery()
    query
      .select('#container')
      .boundingClientRect((res) => {
        this.data.containerScrollTop = res.top - this.data.navStyle.navHeight
      })
      .exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.handlePopup()
    //登录
    let that = this
    const userInfo = wx.getStorageSync('nameInfoObject')
    if (userInfo) {
      that.setData({
        nickName: userInfo.nickName,
        headimg: userInfo.avatarUrl,
        mobile: userInfo.mobile
      })
    }

    let position = wx.getStorageSync('position')
    if (!position) {
      this.getAddressList()
    } else {
      App.globalData.position = position
      this.setData({ position })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.loadmore === 'loading') return
    this.setData({
      loadmore: 'loading'
    })

    this.data.currentPage += 1
    this.getData(this.data.goodsTabType)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    let path = '/pages/home/index' //获取url路径
    return {
      title: '晨熙商城',
      path: path // 路径，传递参数到指定页面。
    }
  },
  onShareTimeline: function (e) {
    return App.onShareTimeline()
  },
  onPageScroll: function (e) {
    this.setData({
      scrollTop: e.scrollTop
    })
    {
      let move = e.scrollTop - this.data.containerScrollTop
      let opacity = move / 20
      if (e.scrollTop > this.data.containerScrollTop) {
        opacity = opacity > 1 ? 1 : opacity.toFixed(2)
        let topDisplay = opacity ? 'block' : 'none'
        this.setData({
          opacity,
          topDisplay
        })
      } else {
        if (opacity !== 0) {
          opacity = 0
          let topDisplay = opacity ? 'block' : 'none'
          this.setData({
            opacity,
            topDisplay
          })
        }
      }
    }
    {
      let move = e.scrollTop
      const distance = App.globalData.navHeight - this.data.navStyle.menuTop
      const searchWidthMax = App.globalData.windowWidth - 20
      const searchWidthMin = this.data.navStyle.menuWidth - 10
      const moveWidth = searchWidthMax - searchWidthMin
      let widthRange = (move / distance).toFixed(2)
      if (move >= distance) {
        widthRange = widthRange > 1 ? 1 : widthRange
        if (!this.data.isSticky) {
          this.setData({
            isSticky: true,
            searchTop: this.data.navStyle.menuTop
          })
        }
      } else {
        if (this.data.isSticky) {
          this.setData({
            isSticky: false,
            searchTop: App.globalData.navHeight
          })
        }
      }

      if (move <= 0) {
        widthRange = 0
      }

      this.setData({
        searchWidth: searchWidthMax - widthRange * moveWidth
      })
    }
  }
})
